/**
* Created by wl
* 项目管理>持有中-详情页-编辑投资减持信息
*/
<template>
    <div class="ca-box ca-box-border-top-none ca-p-20">
        <div class="ca-title">
            <h3>历史变动</h3>
            <div class="ca-pull-right">
                <el-select v-model="changeTypeList" placeholder="请选择" class="ca-wid" @change="filterChangeType(changeTypeList)">
                    <el-option label="全部" value=''></el-option>
                    <el-option
                            v-for="item in dropDown.investChangeType"
                            :label="item.name"
                            :value="item.id"
                            :key="item.id">
                    </el-option>
                </el-select>
                <el-select v-model="fundIdList" placeholder="请选择" class="ca-m-l-10 ca-wid" @change="filterFundId(fundIdList)">
                    <el-option label="全部" value=""></el-option>
                    <el-option
                            v-for="(item, index) in fundNameList"
                            :label="item.fundName"
                            :value="item.fundId"
                            :key="index">
                    </el-option>
                </el-select>
                <el-button type="primary" @click="cancel" size="small">保存</el-button>
                <el-button @click="cancel" size="small">取消</el-button>
            </div>
        </div>
        <div class="ca-m-t-15">

            <table class="ca-table ca-m-t-15" id="historyBox">
                <tr>
                    <th width="12%" class="b_l">投资基金</th>
                    <th width="8%">变动类型</th>
                    <th width="7%">投资类型</th>
                    <th width="8%">变动时间</th>
                    <th width="8%">期初持股数<br />(万股)</th>
                    <th width="8%">变化股数<br />(万股)</th>
                    <th width="7%">期末持股<br />(万股)</th>
                    <th width="7%">变动金额<br />(万元)</th>
                    <th width="8%">变动价格<br />(元/股)</th>
                    <th width="8%">当前成本<br />(元/股)</th>
                    <th width="8%">项目总股本<br />(万股)</th>
                    <th width="7%">项目估值<br />(万元)</th>
                    <th width="7%">退出倍数</th>
                    <th class="b_r">IRR</th>
                    <th class="b_r"><button @click="addHistorical()" class="ca-btn ca-btn-round"><i class="fa fa-plus"></i></button></th>
                </tr>
                <tr v-for="(item, index) in itemHoldInvestEntities" :key="index">
                    <td  class="b_l"><el-button type="text" @click="goIndex(item.fundId)">{{item.fundName}}</el-button></td>
                    <td>{{item.changedType | getNameById('investChangeType')}}</td>
                    <td v-if="item.changedType == 2 || item.changedType == 4">{{item.investType | getNameById('itemExit')}}</td>
                    <td v-else>{{item.investType | getNameById('investType')}}</td>
                    <td>{{$moment(item.investDate).format('YYYY-MM-DD')}}</td>
                    <td>{{item.beginHolding | format1}}</td>
                    <td>{{item.investNumber | format1}}</td>
                    <td>{{item.finalHolding | format1}}</td>
                    <td>{{item.investLoan | format1}}</td>
                    <td>{{item.changeFold | format1}}</td>
                    <td>{{item.currentCost | format1}}</td>
                    <td>{{item.totalCapital}}</td>
                    <td>{{item.valuationAfter | format1}}</td>
                    <td>{{item.exitMultiple}}</td>
                    <td width="8%">{{item.irr | format1}}%</td>
                    <td><el-button type="text" @click="delHistory(item.id)">删除</el-button></td>
                </tr>
            </table>
        </div>
        <el-dialog title="历史变动" :visible.sync="dialogVisible" :show-close="false" @close="closeDialog()">
            <el-form ref="formInvest" label-width="150px" :model="itemHoldInvestEntity" :rules="rules">
                <el-form-item label="变动类型">
                    <el-col :span="8">
                        <el-form-item prop="changedType">
                            <el-select placeholder="请选择变动类型" v-model="itemHoldInvestEntity.changedType" :disabled="changeType" style="width: 100%;" @change="selectType(itemHoldInvestEntity.fundId)">
                                <el-option
                                    v-for="item in dropDown.changeTypeList"
                                    :label="item.name"
                                    :value="item.id"
                                    :key="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col class="el-form-item__label" :span="8">投资基金</el-col>
                    <el-col :span="8">
                        <el-form-item prop="fundId">
                            <el-select placeholder="请选择基金" :title="itemHoldInvestEntity.fundId" v-model="itemHoldInvestEntity.fundId" :disabled="updateType" style="width: 100%;" @change="selectFund(itemHoldInvestEntity.fundId)">
                                <el-option
                                    v-for="(item, index) in fundList"
                                    :label="item.fundName"
                                    :value="item.fundId"
                                    :key="index">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="投资类型">
                    <el-col :span="8">
                        <el-select placeholder="请选择投资类型" v-model="itemHoldInvestEntity.investType" :disabled="investmentType" style="width: 100%;">
                            <el-option
                                v-for="item in dropDown.investType"
                                :label="item.name"
                                :value="item.id"
                                :key="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col class="el-form-item__label" :span="8">变动时间</el-col>
                    <el-col :span="8">
                        <el-form-item prop="investDate">
                            <el-date-picker type="date" placeholder="选择日期" v-model="itemHoldInvestEntity.investDate"
                                            style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="期初持股数（万股）">
                    <el-col :span="8">
                        <el-input type="number" :disabled="formDisabled['Begin_holding']" v-model="itemHoldInvestEntity.beginHolding"></el-input>
                    </el-col>
                    <el-col class="el-form-item__label" :span="8">变化股数（万股）</el-col>
                        <el-col :span="8">
                            <el-form-item prop="investNumber">
                                <el-input type="number" :disabled="formDisabled['invest_number']" v-model="itemHoldInvestEntity.investNumber" @input="monitor()"></el-input>
                            </el-form-item>
                        </el-col>
                </el-form-item>
                <el-form-item label="期末持股（万股）">
                    <el-col :span="8">
                        <el-input type="number" :disabled="formDisabled['Final_holding']" v-model="itemHoldInvestEntity.finalHolding"></el-input>
                    </el-col>
                    <el-col class="el-form-item__label" :span="8">变动金额（万元）</el-col>
                    <el-col :span="8">
                        <el-form-item prop="investLoan">
                            <el-input type="number" :disabled="formDisabled['Total_capital']" v-model="itemHoldInvestEntity.investLoan" @input="monitor()"></el-input>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="变动价格 (元/股)">
                    <el-col :span="8">
                        <el-input type="text" :disabled="true" v-model="itemHoldInvestEntity.changeFold"></el-input>
                    </el-col>
                    <el-col class="el-form-item__label" :span="8">当前成本（元/股）</el-col>
                    <el-col :span="8">
                        <el-input type="number" :disabled="formDisabled['currentCost']" v-model="itemHoldInvestEntity.currentCost"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="项目总股本（万股）">
                    <el-col :span="8">
                        <el-form-item prop="totalCapital">
                            <el-input type="number" :disabled="formDisabled['Total']" v-model="itemHoldInvestEntity.totalCapital" @input="monitor()"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col class="el-form-item__label" :span="8">项目估值（万元）</el-col>
                    <el-col :span="8">
                        <el-form-item prop="valuationAfter">
                            <el-input type="number" :disabled="formDisabled['Project_valuation']" v-model="itemHoldInvestEntity.valuationAfter"></el-input>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="退出倍数">
                    <el-col :span="8">
                        <el-input type="number" :disabled="formDisabled['Exit_multiple']" v-model="itemHoldInvestEntity.exitMultiple" ></el-input>
                    </el-col>
                    <el-col class="el-form-item__label" :span="8">IRR(%)</el-col>
                    <el-col :span="8">
                        <el-form-item prop="irr">
                            <el-input type="number" :disabled="formDisabled['IRR']" v-model="itemHoldInvestEntity.irr"></el-input>
                        </el-form-item>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="save">确 定</el-button>
                <el-button @click="cancelDialog">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script type="text/ecmascript-6">
    import {api} from '../api';
    import {STATUS_HTTP_SUCCESS, apiHttp} from '__service/csHttp';
    export default {
        data() {
            var validateNumber = (rule, value, callback) => {
                var reg = /^\d{1,10}(\.\d{1,6})?$/;
                if (value && !reg.test(value)) {
                    callback(new Error('请输入正确的数字范围'));
                } else {
                    callback();
                }
            };
            let checkChangedType = (rule, value, callback) => {
                if ( this.itemHoldInvestEntity.fundId === '-1' || this.itemHoldInvestEntity.fundId === '') {
                    callback();
                } else if (!value) {
                    return callback(new Error('请选择变动类型'));
                } else {
                    callback();
                }
            };
            return {
                itemHoldInvestEntities: [], //历史记录列表
                dialogVisible: false,
                dropDown: {
                    investChangeType: [
                        {
                            id: '1',
                            name: '初始投资'
                        },
                        {
                            id: '3',
                            name: '增持'
                        },
                        {
                            id: '4',
                            name: '减持'
                        },
                        {
                            id: '5',
                            name: '分红'
                        },
                        {
                            id: '2',
                            name: '退出'
                        },
                        {
                            id: '-1',
                            name: '更新公允价值'
                        },
                    ],
                    changeTypeList: [],
                    investType: this.$store.state.user.dictionaryMap.investType, //投资类型
                },
                changeType: false, // 变动类型
                investmentType: false, //投资类型
                updateType: false, //更新公允价值
                changeTypeList: '', //历史变动类型筛选
                fundIdList: '', //历史基金筛选
                fundNameList: [], //基金筛选列表
                fundList: [],
                reduceNewest: [], //减持前最新数据
                formDisabled: {
                    'Begin_holding': true,          //期初持股数（万股）
                    'invest_number': false,         //变化股数（万股）
                    'Final_holding': true,          //期末持股（万股）
                    'Total_capital': false,         //资金金额（万元）
                    'currentCost': true,             //当前成本（元/股）
                    'Total': false,                 //项目总股本（万股）
                    'Project_valuation': true,     //项目估值（万元）
                    'Exit_multiple': true,         //退出倍数
                    'IRR': true,                    //IRR(%),
                },
                itemHoldInvestEntity: {
                    beginHolding: 0, //期初持股
                    changeFold: 0,  //变动价格
                    changedType: '', //变动类型
                    currentCost: 0, //当前成本
                    exitMultiple: 0, //退出倍数
                    finalHolding: 0, //期末持股
                    fundId: '', //关联基金
                    investDate: '', //投资时间
                    investLoan: 0, //变动金额
                    investNumber: 0, //变化股数
                    investType: '', //投资类型
                    irr: 0, // IRR
                    itemId: this.$route.params.itemId, //项目id
                    totalCapital: 0, //项目总股本
                    valuationAfter: 0, //投后项目估值
                    valuationBefore: 0, //投前项目估值
                },
                changedTypeList1: [], //初始投资
                changedTypeList2: [], //退出
                changedTypeList3: [], //增持
                changedTypeList4: [], //减持
                changedTypeList5: [], //分红
                changedTypeList6: [], //更新公允价值（未投资）
                rules: {
                    fundId: [{required: true, message: '请选择基金', trigger: 'change'}],
                    changedType: [{ validator: checkChangedType, message: '请选择变动类型', trigger: 'change'}],
                    investDate: [{type: 'date',required: true, message: '请选择日期', trigger: 'change'}],
                    investNumber: [{ validator: validateNumber, trigger: 'blur' }], //变化股数
                    investLoan: [{ validator: validateNumber, trigger: 'blur' }], //变动金额
                    totalCapital: [{ validator: validateNumber, trigger: 'blur' }], //项目总股本
                    // valuationAfter: [{ validator: validateNumber, trigger: 'blur' }], //项目估值
                    irr: [{ validator: validateNumber, trigger: 'blur' }], //irr
                },
            }
        },
        watch: {
        },
        props: {
        },
        mounted() {
            this.checkHistory()
            this.getList()
            this.init()
            this.getFundList()
        },
        methods: {
            // 基金跳转
            goIndex(id) {
                this.$router.push({name: 'investing-funds', params: {fundId: id, tabIndex: 0, openWindow: true }});
            },
            // 查看历史变动数据
            checkHistory() {
                let query = {
                    itemId: this.$route.params.itemId,
                    fundId: '',
                    changedType: '', //变动类型
                    investType: null, //投资类型
                }
                apiHttp(api.CHECK_HISTORY, query).then(ret=> {
                    if (ret.resCode === STATUS_HTTP_SUCCESS) {
                        this.itemHoldInvestEntities = ret.data.itemHoldInvestEntities
                        let changeType = this.dropDown.investChangeType
                        // 判断是不是初次进入
                        if (this.itemHoldInvestEntities.length === 0) {
                            this.dropDown.changeTypeList = []
                            changeType.map( item => {
                                if (item.id === '1') {
                                    this.dropDown.changeTypeList[0] = item
                                }
                            })
                        } else {
                            this.dropDown.changeTypeList = changeType
                        }
                    }
                })
            },
            // 基金筛选列表
            getFundList() {
                let query = {
                    itemId: this.$route.params.itemId,
                    fundId: '',
                    changedType: '', //变动类型
                    investType: null, //投资类型
                }
                apiHttp(api.CHECK_HISTORY, query).then(ret=> {
                    if (ret.resCode === STATUS_HTTP_SUCCESS) {
                        this.fundNameList = []
                        this.itemHoldInvestEntities = ret.data.itemHoldInvestEntities
                        if (this.itemHoldInvestEntities.length > 0) {
                            for (var i = 0; i < this.itemHoldInvestEntities.length; i++) {
                                var flag = true
                                for (var j = 0; j < this.fundNameList.length; j++) {
                                    if (this.itemHoldInvestEntities[i].fundId === this.fundNameList[j].fundId || this.itemHoldInvestEntities[i].fundId === '-1') {
                                        flag = false
                                    }
                                }
                                if (flag) {
                                    this.fundNameList.push(this.itemHoldInvestEntities[i])
                                }
                            }
                        }
                    }
                })
            },
            // 筛选
            filterFundId(fundId) {
                this.fundIdList = fundId
                let query = {
                    itemId: this.$route.params.itemId,
                    fundId: fundId,
                    changedType: this.changeTypeList, //变动类型
                    investType: null, //投资类型
                }
                apiHttp(api.CHECK_HISTORY, query).then(ret=> {
                    if (ret.resCode === STATUS_HTTP_SUCCESS) {
                        this.itemHoldInvestEntities = ret.data.itemHoldInvestEntities
                    }
                })
            },
            // 筛选
            filterChangeType(changedType) {
                this.changeTypeList = changedType
                let query = {
                    itemId: this.$route.params.itemId,
                    fundId: this.fundIdList,
                    changedType: changedType, //变动类型
                    investType: null, //投资类型
                }
                apiHttp(api.CHECK_HISTORY, query).then(ret=> {
                    if (ret.resCode === STATUS_HTTP_SUCCESS) {
                        this.itemHoldInvestEntities = ret.data.itemHoldInvestEntities
                    }
                })
            },
            // 获取已设立基金列表
            getList() {
                apiHttp(api.GET_LIST).then(ret=> {
                    if (ret.resCode === STATUS_HTTP_SUCCESS) {
                        // 去掉已退出项目
                        let exitList = []
                        this.itemHoldInvestEntities.map(item => {
                            if (item.changedType === 2) {
                                exitList.push(item)
                            }
                        })
                        if (exitList.length > 0) {
                            this.fundList = []
                            for ( var index in ret.data ) {
                                for (var ind in exitList ) {
                                    if (ret.data[index].fundName !== exitList[ind].fundName) {
                                        this.fundList.push({fundId: ret.data[index].id, fundName: ret.data[index].fundName})
                                    }
                                }
                            }
                        } else {
                            ret.data.map(item => {
                                this.fundList.push({fundId: item.id, fundName: item.fundName})
                            })
                        }
                    }
                })
            },
            // 删除
            delHistory(id) {
                let that = this
                let query = {
                    itemId: this.$route.params.itemId,
                    historyId: id
                }
                this.$confirm('是否确认删除此条项目?', '提示', {
                    cancelButtonText: '取消',
                    confirmButtonText: '确定',
                    type: 'warning',
                    showClose: false,
                }).then(async () => {
                    apiHttp(api.DEL_HISTORY, query).then(ret => {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            that.$message({
                                message: '数据删除成功！',
                                type: 'success',
                                center: true
                            });
                            that.$emit('save')
                            that.$emit('updateList')
                            this.checkHistory()
                        }
                    })
                });
            },
            // 取消
            cancelDialog() {
                this.dialogVisible = false
                this.init()
                this.$emit('updateList')
            },
            // 选择变动类型
            selectType() {
                this.itemHoldInvestEntity.fundId = ''
                if (this.itemHoldInvestEntity.changedType === '1') { // 变动类型为初始投资
                    this.investmentType = false //投资类型可选
                    this.updateType = false //选择基金可选
                    this.dropDown.investType = this.$store.state.user.dictionaryMap.investType //投资类型
                    this.itemHoldInvestEntity.investType = '1' //选择默认的投资类型
                    this.controlDisabled()
                    this.itemHoldInvestEntity.beginHolding = 0
                    this.itemHoldInvestEntity.finalHolding = 0
                    this.itemHoldInvestEntity.currentCost = 0
                    this.itemHoldInvestEntity.totalCapital = 0
                    this.itemHoldInvestEntity.valuationAfter = 0
                    this.itemHoldInvestEntity.irr = 0 // IRR
                    // 选出所有需要初始投资的基金
                    this.getInitial('init')
                } else if (this.itemHoldInvestEntity.changedType === '2') {  // 变动类型为退出
                    this.getInitial('times')
                    this.newestData(this.itemHoldInvestEntity.fundId)
                    this.investmentType = false //投资类型可选
                    this.updateType = false //选择基金可选
                    this.dropDown.investType = this.$store.state.user.dictionaryMap.itemExit //投资类型
                    this.itemHoldInvestEntity.investType = '1' //选择默认的投资类型
                    this.controlDisabled()
                    this.formDisabled.IRR = false
                    this.itemHoldInvestEntity.currentCost = 0
                    this.itemHoldInvestEntity.totalCapital = 0
                    this.itemHoldInvestEntity.valuationAfter = 0
                    this.itemHoldInvestEntity.exitMultiple = 0
                    this.itemHoldInvestEntity.irr = 0 // IRR
                } else if (this.itemHoldInvestEntity.changedType === '3') {  // 变动类型为增持
                    this.getInitial('times')
                    this.newestData(this.itemHoldInvestEntity.fundId)
                    this.investmentType = false //投资类型可选
                    this.updateType = false //选择基金可选
                    this.dropDown.investType = this.$store.state.user.dictionaryMap.investType //投资类型
                    this.itemHoldInvestEntity.investType = '1' //选择默认的投资类型
                    this.controlDisabled()
                    this.itemHoldInvestEntity.currentCost = 0
                    this.itemHoldInvestEntity.totalCapital = 0
                    this.itemHoldInvestEntity.valuationAfter = 0
                    this.itemHoldInvestEntity.irr = 0 // IRR
                } else if (this.itemHoldInvestEntity.changedType === '4') {  // 变动类型为减持
                    this.getInitial('times')
                    this.newestData(this.itemHoldInvestEntity.fundId)
                    this.investmentType = false //投资类型可选
                    this.updateType = false //选择基金可选
                    this.dropDown.investType = this.$store.state.user.dictionaryMap.itemExit //投资类型
                    this.itemHoldInvestEntity.investType = '1' //选择默认的投资类型
                    this.controlDisabled()
                    this.itemHoldInvestEntity.currentCost = 0
                    this.itemHoldInvestEntity.totalCapital = 0
                    this.itemHoldInvestEntity.valuationAfter = 0
                    this.itemHoldInvestEntity.irr = 0 // IRR
                } else if (this.itemHoldInvestEntity.changedType === '5') {  // 变动类型为分红
                    this.getInitial('times')
                    this.newestData(this.itemHoldInvestEntity.fundId)
                    this.investmentType = true //投资类型不可选
                    this.updateType = false //选择基金可选
                    this.itemHoldInvestEntity.investType = ''
                    this.formDisabled.Total_capital = false //变动金额（万元）
                    this.formDisabled.Total = true //项目总股本（万股）
                    this.formDisabled.Project_valuation = true //项目估值（万元）
                    this.formDisabled.IRR = true
                    this.formDisabled.invest_number = true //变化股数（万股）
                    this.formDisabled.Total = true //项目总股本（万股）
                    this.itemHoldInvestEntity.irr = 0 // IRR
                } else if (this.itemHoldInvestEntity.changedType === '-1') { // 变动类型为更新公允价值
                    this.investmentType = true //投资类型不可选
                    this.updateType = true //选择基金不可选
                    this.itemHoldInvestEntity.fundId = '' //投资基金默认为-1
                    this.itemHoldInvestEntity.investType = ''
                    this.itemHoldInvestEntity.beginHolding = 0
                    this.itemHoldInvestEntity.finalHolding = 0
                    this.itemHoldInvestEntity.currentCost = 0
                    this.itemHoldInvestEntity.totalCapital = 0
                    this.itemHoldInvestEntity.valuationAfter = 0
                    this.formDisabled.Total = false //项目总股本（万股）
                    this.formDisabled.Project_valuation = false //项目估值（万元）
                    this.formDisabled.Begin_holding = true          //期初持股数（万股）
                    this.formDisabled.invest_number = true      //变化股数（万股）
                    this.formDisabled.Final_holding = true         //期末持股（万股）
                    this.formDisabled.Total_capital = true       //资金金额（万元）
                    this.formDisabled.currentCost = true             //当前成本（元/股）
                    this.formDisabled.Exit_multiple = true      //退出倍数
                    this.formDisabled.IRR = true                //IRR(%),
                    this.itemHoldInvestEntity.irr = 0 // IRR
                }
            },
            // 类型为增持、减持、初始投资控制disabled
            controlDisabled() {
                this.formDisabled.Begin_holding = true //期初持股数（万股）
                this.formDisabled.invest_number = false //变化股数（万股）
                this.formDisabled.Final_holding = true //期末持股（万股）
                this.formDisabled.Total_capital = false //变动金额（万元）
                this.formDisabled.currentCost = true //当前成本（元/股）
                this.formDisabled.Total = false //项目总股本（万股）
                this.formDisabled.Project_valuation = true //项目估值（万元）
                this.formDisabled.Exit_multiple = true //退出倍数
                this.formDisabled.IRR = true //IRR(%)
            },
            // 选择投资基金
            selectFund(id) {
                if (id) { //选择投资基金后变动类型和投资类型可选
                    this.newestData(id)
                }
                let exitList = []
                this.itemHoldInvestEntities.map(item => {
                    if (this.itemHoldInvestEntity.fundId === item.fundId) {
                        exitList.push(item)
                    }
                })
                exitList.map(val => {
                    if (val.changedType === 1) {
                        this.changedTypeList1.push(val)
                    } else if (val.changedType === 2) {
                        this.changedTypeList2.push(val)
                    } else if (val.changedType === 3) {
                        this.changedTypeList3.push(val)
                    } else if (val.changedType === 4) {
                        this.changedTypeList4.push(val)
                    } else if (val.changedType === 5) {
                        this.changedTypeList5.push(val)
                    } else {
                        this.changedTypeList6.push(val)
                    }
                })
            },
            // 查找最近一条数据
            newestData(id) {
                let list = []
                // 找到同一基金
                this.itemHoldInvestEntities.map(item => {
                    if (item.fundId === id) {
                        list.push(item)
                    }
                })
                var listDate = []
                for (var i in list) {
                    listDate.push(list[i].investDate);
                    listDate.push(list[i].fundId);
                }
                listDate.sort(function (num1, num2) {
                    return num1 - num2;
                })
                // 找最新数据
                this.itemHoldInvestEntities.map(val => {
                    // 在相同基金的情况下取最新数据
                    if (val.fundId === listDate[listDate.length - 1]) {
                        if (val.investDate === listDate[listDate.length - 2]) {
                            this.reduceNewest = val
                            this.itemHoldInvestEntity.beginHolding = this.reduceNewest.finalHolding
                            this.itemHoldInvestEntity.finalHolding = this.reduceNewest.finalHolding
                            if (this.itemHoldInvestEntity.changedType === '5') { //分红
                                this.itemHoldInvestEntity.currentCost = this.reduceNewest.currentCost
                                this.itemHoldInvestEntity.totalCapital = this.reduceNewest.totalCapital
                                this.itemHoldInvestEntity.valuationAfter = this.reduceNewest.valuationAfter
                            }
                        }
                    }
                })
            },
            // 监听变化
            monitor() {
                if (this.itemHoldInvestEntity.changedType === '1') { //初始投资
                    // 期末持股=变化股数
                    this.itemHoldInvestEntity.finalHolding = Number(this.itemHoldInvestEntity.investNumber)
                    // 变动价格=变动金额/变化股数
                    this.itemHoldInvestEntity.changeFold = Number(this.itemHoldInvestEntity.investLoan) / Number(this.itemHoldInvestEntity.investNumber)
                    // 当前成本=变动金额/变化股数
                    this.itemHoldInvestEntity.currentCost = this.itemHoldInvestEntity.changeFold
                    // 项目估值=当前成本*项目总股本
                    this.itemHoldInvestEntity.valuationAfter = Number(this.itemHoldInvestEntity.currentCost) * Number(this.itemHoldInvestEntity.totalCapital)
                    // this.sixBits()
                } else if (this.itemHoldInvestEntity.changedType === '2') { //退出
                    // 期末持股=期初持股数-变化股数
                    this.itemHoldInvestEntity.finalHolding = Number(this.itemHoldInvestEntity.beginHolding) - Number(this.itemHoldInvestEntity.investNumber)
                    // 变动价格=变动金额/变化股数
                    this.itemHoldInvestEntity.changeFold = Number(this.itemHoldInvestEntity.investLoan) / Number(this.itemHoldInvestEntity.investNumber)
                    // 项目估值=变动价格*项目总股本
                    this.itemHoldInvestEntity.valuationAfter = Number(this.itemHoldInvestEntity.changeFold) * Number(this.itemHoldInvestEntity.totalCapital)
                    // 退出倍数
                    this.itemHoldInvestEntity.exitMultiple = (Number(this.itemHoldInvestEntity.investLoan) + this.sum(this.changedTypeList4) + this.sum(this.changedTypeList5)) / (this.sum(this.changedTypeList1) + this.sum(this.changedTypeList3))
                    // this.sixBits()
                } else if (this.itemHoldInvestEntity.changedType === '3') { //增持
                    // 期末持股=期初持股数+变化股数
                    this.itemHoldInvestEntity.finalHolding = Number(this.itemHoldInvestEntity.beginHolding) + Number(this.itemHoldInvestEntity.investNumber)
                    // 变动价格=变动金额/变化股数
                    this.itemHoldInvestEntity.changeFold = Number(this.itemHoldInvestEntity.investLoan) / Number(this.itemHoldInvestEntity.investNumber)
                    // 项目估值=变动价格*项目总股本
                    this.itemHoldInvestEntity.valuationAfter = Number(this.itemHoldInvestEntity.changeFold) * Number(this.itemHoldInvestEntity.totalCapital)
                    // 当前成本=【初始投资金额+增持金额-减持股数X减持前持股单价】/期末持股数量
                    if (this.itemHoldInvestEntity.investLoan !== 0) {
                        this.itemHoldInvestEntity.currentCost = (this.sum(this.changedTypeList1) + this.sum(this.changedTypeList3) - this.reduceSum(this.changedTypeList4) + Number(this.itemHoldInvestEntity.investLoan)) / this.itemHoldInvestEntity.finalHolding
                    }
                    // this.sixBits()
                } else if (this.itemHoldInvestEntity.changedType === '4') { //减持
                    // 期末持股=期初持股数-变化股数
                    this.itemHoldInvestEntity.finalHolding = Number(this.itemHoldInvestEntity.beginHolding) - Number(this.itemHoldInvestEntity.investNumber)
                    // 变动价格=变动金额/变化股数
                    this.itemHoldInvestEntity.changeFold = Number(this.itemHoldInvestEntity.investLoan) / Number(this.itemHoldInvestEntity.investNumber)
                    // 项目估值=变动价格*项目总股本
                    this.itemHoldInvestEntity.valuationAfter = Number(this.itemHoldInvestEntity.changeFold) * Number(this.itemHoldInvestEntity.totalCapital)
                    // 当前成本=最近一次数据的当前成本
                    this.itemHoldInvestEntity.currentCost = this.reduceNewest.currentCost
                    // this.sixBits()
                }
            },
            // 取消
            cancel() {
                this.$emit('close')
            },
            // 添加历史记录
            addHistorical() {
                this.dialogVisible = true
            },
            // 保存
            save() {
                if (this.itemHoldInvestEntity.changedType === '-1') { //更新公允价值基金为-1
                    this.itemHoldInvestEntity.fundId = '-1' //投资基金默认为-1
                }
                this.$refs.formInvest.validate((valid) => {
                    if (valid) {
                        // if (this.itemHoldInvestEntity.changedType === '5') { //如果为分红则最后期末股数为0
                        //     this.itemHoldInvestEntity.finalHolding = 0
                        // }
                        let query = {
                            itemId: this.$route.params.itemId,
                            itemHoldInvestEntity: this.itemHoldInvestEntity
                        }
                        apiHttp(api.CREATE_HISTORY, query).then(ret=> {
                            if (ret.resCode === STATUS_HTTP_SUCCESS) {
                                this.$message({
                                    message: '修改成功！',
                                    type: 'success'
                                });
                                this.checkHistory()
                                this.$emit('save')
                                this.init()
                                this.dialogVisible = false;
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            // 初始化值
            init() {
                this.itemHoldInvestEntity.beginHolding = 0 //期初持股
                this.itemHoldInvestEntity.changeFold = 0  //变动价格
                this.itemHoldInvestEntity.changedType = '' //变动类型
                this.itemHoldInvestEntity.currentCost = 0 //当前成本
                this.itemHoldInvestEntity.exitMultiple = 0 //退出倍数
                this.itemHoldInvestEntity.finalHolding = 0 //期末持股
                this.itemHoldInvestEntity.fundId = '' //关联基金 -1代表 未投资
                this.itemHoldInvestEntity.investDate = null //投资时间
                this.itemHoldInvestEntity.investLoan = 0 //变动金额
                this.itemHoldInvestEntity.investNumber = 0 //变化股数
                this.itemHoldInvestEntity.investType = '' //投资类型
                this.itemHoldInvestEntity.irr = 0 // IRR
                this.itemHoldInvestEntity.totalCapital = 0 //项目总股本
                this.itemHoldInvestEntity.valuationAfter = 0 //投后项目估值
                this.itemHoldInvestEntity.valuationBefore = 0 //投前项目估值
                this.changedTypeList1 = [] //初始投资
                this.changedTypeList2 = [] //退出
                this.changedTypeList3 = [] //增持
                this.changedTypeList4 = [] //减持
                this.changedTypeList5 = [] //分红
                this.changedTypeList6 = [] //更新公允价值（未投资）
                this.changeType = false
                this.investmentType = false
                this.updateType = false //选择基金可选
            },
            // 求和
            sum(arr) {
                let sum = 0
                if (arr.length === 0) {
                    return sum
                } else {
                    arr.forEach(val => {
                        sum += val.investLoan
                    })
                    return sum
                }
            },
            // 取减持股数*减持前持股单价
            reduceSum(arr) {
                let reduceSum = 0
                if (arr.length === 0) {
                    return reduceSum
                } else {
                    arr.forEach(val => {
                        reduceSum += val.investNumber * val.currentCost
                    })
                    return reduceSum
                }
            },
            // 筛选出所有需要初始投资的基金或除初始投资以外的基金
            getInitial(type) {
                apiHttp(api.GET_LIST).then(ret=> {
                    if (ret.resCode === STATUS_HTTP_SUCCESS) {
                        // 所有基金
                        let allFundList = []
                        // 已退出项目
                        let exitList = []
                        this.itemHoldInvestEntities.map(item => {
                            if (item.changedType === 2) {
                                exitList.push(item)
                            }
                        })
                        // 找出初始投资
                        if (type === 'init') {
                            // 存在退出项目
                            if (exitList.length > 0) {
                                this.fundList = []
                                for ( var index in ret.data ) {
                                    for (var ind in exitList ) {
                                        if (ret.data[index].fundName !== exitList[ind].fundName) {
                                            allFundList.push({fundId: ret.data[index].id, fundName: ret.data[index].fundName})
                                        }
                                    }
                                }
                                let arr = []
                                this.itemHoldInvestEntities.forEach((v) => {
                                    arr[v.fundId] = true
                                })
                                this.fundList = allFundList.filter((v) => !arr[v.fundId])
                            // 不存在退出项目
                            } else {
                                this.fundList = []
                                ret.data.map(item => {
                                    allFundList.push({fundId: item.id, fundName: item.fundName})
                                })
                                if (this.itemHoldInvestEntities.length > 0) {
                                    let arr = []
                                    this.itemHoldInvestEntities.forEach((v) => {
                                        arr[v.fundId] = true
                                    })
                                    this.fundList = allFundList.filter((v) => !arr[v.fundId])
                                } else {
                                    this.fundList = allFundList
                                }
                            }
                        // 找出非初始投资
                        } else {
                            // console.log(this.exitList,'sds')
                            if (exitList.length > 0) { //存在已退出项目
                                this.fundList = []
                                this.fundList = this.screenArr(this.itemHoldInvestEntities)
                            } else { //不存在已退出
                                this.fundList = []
                                for (var i = 0; i < this.itemHoldInvestEntities.length; i++) {
                                    var flag = true
                                    for (var j = 0; j < this.fundList.length; j++) {
                                        if (this.itemHoldInvestEntities[i].fundId === this.fundList[j].fundId) {
                                            flag = false;
                                            }
                                        }
                                        if (this.itemHoldInvestEntities[i].fundId === '-1') {
                                            flag = false;
                                        }
                                    if (flag) {
                                        this.fundList.push(this.itemHoldInvestEntities[i]);
                                    }
                                }
                            }
                        }
                    }
                })
            },
            screenArr(arr) {
                let newArr = []
                let str = []
                arr.forEach((v) => {
                    if (v.changedType === 2 || v.changedType === -1) { // 已退出和更新公允价值
                        newArr.push(v.fundId)
                    }
                })
                arr.forEach((v) => { // 筛选
                    if (newArr.indexOf(v.fundId) === -1) {
                        str.push(v)
                    }
                })
                let newFundList = []
                for (var i = 0; i < str.length; i++) {
                    var flag = true
                    for (var j = 0; j < newFundList.length; j++) {
                        if (str[i].fundId === newFundList[j].fundId) {
                            flag = false;
                            }
                        }
                        if (str[i].fundId === '-1') {
                            flag = false;
                        }
                    if (flag) {
                        newFundList.push(str[i]);
                    }
                }
                // console.log(str.includes('D6F1786FDF184B0E939001364BA6C2EA'),'arr')
                return newFundList
            },
            // 小数点后保留六位
            sixBits() {
                if (this.formDisabled.Begin_holding === true) { //期初持股数
                    this.saveSix(this.itemHoldInvestEntity.beginHolding)
                }
                if (this.formDisabled.invest_number === true) { //变化股数
                    this.saveSix(this.itemHoldInvestEntity.investNumber)
                }
                if (this.formDisabled.Final_holding === true) { //期末持股数
                    this.saveSix(this.itemHoldInvestEntity.finalHolding)
                }
                if (this.formDisabled.Total_capital === true) { //变动金额
                    this.saveSix(this.itemHoldInvestEntity.investLoan)
                }
                if (this.formDisabled.currentCost === true) { //当前成本
                    this.saveSix(this.itemHoldInvestEntity.currentCost)
                }
                if (this.formDisabled.Total === true) { //项目总股本
                    this.saveSix(this.itemHoldInvestEntity.totalCapital)
                }
                if (this.formDisabled.Project_valuation === true) { //投后项目估值
                    this.saveSix(this.itemHoldInvestEntity.valuationAfter)
                }
                if (this.formDisabled.Exit_multiple === true) { //退出倍数
                    this.saveSix(this.itemHoldInvestEntity.exitMultiple)
                }
                if (this.formDisabled.IRR === true) { //irr
                    this.saveSix(this.itemHoldInvestEntity.irr)
                }
            },
            saveSix(value) {
                if (!Number.isInteger(value) && value.toString().split('.')[1].length > 6) {
                    return value.toFixed(6)
                }
            },
            // dialog关闭
            closeDialog() {
                this.init()
                this.checkHistory()
                this.getFundList()
            },
        },
        components: {
        },
    }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.ca-wid {
    width: 150px;
}
.ca-table th {
    line-height: 20px;
}
</style>
